import { useState, useEffect } from 'react'

import { stringToJson } from '@/utils/stringUtil'

const LocalCachePack = ({ children, uuid, tagType, valueProps = 'value', ...others }) => {
  const Tag = tagType || children.type
  const key = 'LocalCachePack' + uuid
  const [v, setV] = useState(others[valueProps])

  useEffect(() => {
    setV(others[valueProps])
  }, [others])

  const childrenProps = { ...children.props, [valueProps]: v }

  const onChange = e => {
    const tmp = e && e.target ? e.target[valueProps] : e
    setV(tmp)
    try {
      window.localStorage.setItem(key, JSON.stringify(tmp))
    } catch (err) {
      console.error(err)
    }
    childrenProps.onChange && childrenProps.onChange(e)
    others && others.onChange && others.onChange(e)
  }
  if (!Tag) {
    return children
  }
  return <Tag {...others} {...childrenProps} onChange={onChange} />
}

/**
 * 获取组件上一次操作之后缓存的值
 * @param uuid
 * @param whenNullReturnValue 如果本地没有记录返回何值， 默认是undefined
 * @returns {null}
 */
LocalCachePack.getLastValue = (uuid, whenNullReturnValue = undefined) => {
  const key = 'LocalCachePack' + uuid
  let v
  try {
    v = stringToJson(window.localStorage.getItem(key))
  } catch (err) {
    console.error(err)
  }
  if (![null, undefined].includes(whenNullReturnValue) && [null, undefined].includes(v)) {
    v = whenNullReturnValue
  }
  return v
}

export default LocalCachePack
